<?php

namespace app\common\service;

use EasyWeChat\Factory;

class OfficialService
{
    protected $app;

    public function __construct()
    {
        $config = [
            'app_id' => 'wxe09c55a05bd71e79',
            'secret' => 'your_app_secret',
        ];

        $this->app = Factory::officialAccount($config);
    }

    /**
     * 发送模板消息
     * @param string $openid
     * @param string $templateId
     * @param array $data
     * @param string $url
     * @param array $miniprogram
     * @return array
     */
    public function sendTemplateMessage(string $openid, string $templateId, array $data, string $url = '', array $miniprogram = []): array
    {
        $message = [
            'touser' => $openid,
            'template_id' => $templateId,
            'url' => $url,
            'data' => $data,
            'miniprogram' => $miniprogram,
        ];

        try {
            $result = $this->app->template_message->send($message);
            return $result;
        } catch (\Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
            ];
        }
    }
}